﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;

namespace CCWpf.Utils
{
    public class WindowManager
    {
        public static Hashtable registerWindow = new Hashtable();//注册的页面键值对
        /// <summary>
        /// 泛型方法注册窗口或者page
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="key"></param>
        public static void Register<T>(string key)
        { 
            if (!registerWindow.ContainsKey(key))
                registerWindow.Add(key, typeof(T));
        }
        /// <summary>
        /// 注册窗口或者page
        /// </summary>
        /// <param name="key"></param>
        /// <param name="type"></param>
        public static void Register(string key, Type type)
        { 
            if (!registerWindow.ContainsKey(key))
                registerWindow.Add(key, type);
        }
        /// <summary>
        /// 打开窗口
        /// </summary>
        /// <param name="key"></param>
        /// <param name="objVM"></param>
        /// <param name="isDialog"></param>
        /// <exception cref="Exception"></exception>
        public static void ShowWindow(string key, object objVM, bool isDialog)
        {
            if (!registerWindow.ContainsKey(key))
            { 
                throw new Exception("未注册此键");
            }
            var win = (Window)Activator.CreateInstance((Type)registerWindow[key]!)!;//创建窗口对象
            if (objVM != null)
                win.DataContext = objVM;//绑定数据上下文
            win.WindowStartupLocation = WindowStartupLocation.CenterScreen;
            if (isDialog)
                win.ShowDialog();
            else
                win.Show();
        }
        /// <summary>
        /// 关闭窗口
        /// </summary>
        /// <param name="key"></param>
        /// <param name="win"></param>
        /// <exception cref="Exception"></exception>
        public static void CloseWindow(string key,object win)
        {
            if (!registerWindow.ContainsKey(key))
            {
                throw new Exception("未注册此键");
            }
            if (win != null)
            {
                Window window=win as Window;
                window.Close();
            }
        }

        public static object CreatePageInstance(string key, object objVM)
        {
            if (!registerWindow.ContainsKey(key))
            {
                throw new Exception("未注册此键");
            }
            Type type= (Type)registerWindow[key]!;
            var instance = (Page)Activator.CreateInstance(type!)!;
            instance.DataContext = objVM;
            return instance;
        }
    }
}
